import { updateUserPassword, userLogout } from '@/services/userService';
import { Link } from '@@/exports';
import { KeyOutlined, LogoutOutlined } from '@ant-design/icons';
import { useModel } from '@umijs/max';
import { Avatar, Button, Dropdown, Form, Input, Menu, message, Modal } from 'antd';
import classNames from 'classnames';
import { stringify } from 'querystring';
import React from 'react';
import { history } from 'umi';
import styles from './index.less';

/**
 * 头像下拉菜单
 *
 * @constructor
 * @author https://github.com/liyupi
 */
const AvatarDropdown: React.FC = () => {
  const { initialState, setInitialState } = useModel('@@initialState');
  const [isChangePasswordVisible, setIsChangePasswordVisible] = React.useState(false);
  const [form] = Form.useForm();
  const loginUser = initialState?.loginUser;

  const onMenuClick = async (event: {
    key: React.Key;
    keyPath: React.Key[];
  }) => {
    const { key } = event;

    if (key === 'changePassword') {
      setIsChangePasswordVisible(true);
      return;
    }

    if (key === 'logout') {
      try {
        await userLogout();
        message.success('已退出登录');
      } catch (e: any) {
        message.error('操作失败');
      }
      // @ts-ignore
      await setInitialState({ ...initialState, loginUser: undefined });
      history.replace({
        pathname: '/user/login',
        search: stringify({
          redirect: window.location.href,
        }),
      });
      return;
    }
  };

  /**
   * 下拉菜单
   */
  const menuHeaderDropdown = loginUser ? (
    <Menu className={styles.menu} selectedKeys={[]} onClick={onMenuClick}>
      <Menu.Item key="current" disabled>
        {loginUser.userName ?? '无名'}
      </Menu.Item>
      <Menu.Item key="changePassword">
        <KeyOutlined />
        修改密码
      </Menu.Item>
      <Menu.Item key="logout">
        <span style={{ color: 'red' }}>
          <LogoutOutlined />
          退出登录
        </span>
      </Menu.Item>
    </Menu>
  ) : (
    <></>
  );

  /**
   * 处理修改密码
   */
  const handleChangePassword = async (values: any) => {
    try {
      await updateUserPassword({
        oldPassword: values.oldPassword,
        newPassword: values.newPassword,
        checkPassword: values.confirmPassword,
      });
      message.success('密码修改成功，请重新登录');
      setIsChangePasswordVisible(false);
      form.resetFields();
      
      // 修改密码成功后自动退出登录
      try {
        await userLogout();
      } catch (e: any) {
        console.error('退出登录失败', e);
      }
      
      // 清除登录状态
      await setInitialState({ ...initialState, loginUser: undefined });
      
      // 跳转到登录页面
      history.replace({
        pathname: '/user/login',
        search: stringify({
          redirect: window.location.href,
        }),
      });
    } catch (e: any) {
      message.error('修改失败，' + e.message);
    }
  };

  // 修改密码对话框
  const passwordModal = (
    <Modal
      title="修改密码"
      visible={isChangePasswordVisible}
      onCancel={() => {
        setIsChangePasswordVisible(false);
        form.resetFields();
      }}
      footer={null}
    >
      <Form form={form} onFinish={handleChangePassword}>
        <Form.Item
          name="oldPassword"
          label="原密码"
          rules={[{ required: true, message: '请输入原密码' }]}
        >
          <Input.Password placeholder="请输入原密码" />
        </Form.Item>
        <Form.Item
          name="newPassword"
          label="新密码"
          rules={[{ required: true, message: '请输入新密码' }]}
        >
          <Input.Password placeholder="请输入新密码" />
        </Form.Item>
        <Form.Item
          name="confirmPassword"
          label="确认密码"
          rules={[
            { required: true, message: '请确认新密码' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('newPassword') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次输入的密码不一致'));
              },
            }),
          ]}
        >
          <Input.Password placeholder="请再次输入新密码" />
        </Form.Item>
        <Form.Item style={{ textAlign: 'right' }}>
          <Button
            style={{ marginRight: 8 }}
            onClick={() => {
              setIsChangePasswordVisible(false);
              form.resetFields();
            }}
          >
            取消
          </Button>
          <Button type="primary" htmlType="submit">
            确定
          </Button>
        </Form.Item>
      </Form>
    </Modal>
  );

  return loginUser ? (
    <>
      <Dropdown
        overlayClassName={classNames(styles.container)}
        overlay={menuHeaderDropdown}
      >
        <div className={`${styles.action} ${styles.account}`}>
          <Avatar>{loginUser.userName?.[0] ?? '无'}</Avatar>
        </div>
      </Dropdown>
      {passwordModal}
    </>
  ) : (
    <>
      <Link to="/user/login">
        <Button type="primary" ghost style={{ marginRight: 16 }}>
          登录
        </Button>
      </Link>
    </>
  );
};

export default AvatarDropdown;
